<script setup lang="ts">
  import { queryList } from '@/api/system/menu';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import { computed, ref } from 'vue';

  const props = defineProps({
    disabled: Boolean,
  });

  const checkedKeys = defineModel<string[]>('checkedKeys');

  const checkedKeysVal = computed<string[]>({
    get() {
      return checkedKeys.value as string[];
    },
    set(val) {
      if (props.disabled) {
        return;
      }
      checkedKeys.value = val;
    },
  });

  const allKeys = ref<string[]>([]);

  const getPermissionId = (data: any[]) => {
    const ids: string[] = [];

    const level = (arr: any[]) => {
      arr.forEach((e) => {
        ids.push(e.id);
        if (e.permissions && e.permissions.length > 0) {
          level(e.permissions);
        }
      });
    };

    level(data);

    return ids;
  };

  const treeView = useSkeleton({
    apiFun: queryList,
    onSuccess(data) {
      allKeys.value = getPermissionId(data);
    },
  });

  const fieldNames = {
    key: 'id',
    title: 'name',
    children: 'permissions',
  };

  const checkAllStatus = computed(() => {
    if (checkedKeysVal.value.length === 0) {
      return {
        indeterminate: false,
        checkedAll: false,
      };
    }
    if (checkedKeysVal.value.length === allKeys.value.length) {
      return {
        indeterminate: false,
        checkedAll: true,
      };
    }

    return {
      indeterminate: true,
      checkedAll: false,
    };
  });

  const handleChangeAll = (value: any) => {
    if (value) {
      checkedKeysVal.value = allKeys.value;
    } else {
      checkedKeysVal.value = [];
    }
  };
</script>

<template>
  <div class="col">
    <skeleton-view v-slot="{ data }" v-bind="treeView.bindProps">
      <a-checkbox
        :model-value="checkAllStatus.checkedAll"
        :indeterminate="checkAllStatus.indeterminate"
        @change="handleChangeAll"
        >全选
      </a-checkbox>
      <a-tree
        v-model:checked-keys="checkedKeysVal"
        :field-names="fieldNames"
        :data="data"
        :checkable="true"
        :check-strictly="true"
        :default-expand-all="false"
        v-bind="$attrs"
      />
    </skeleton-view>
  </div>
</template>

<style lang="less" scoped></style>
